package com.guozinhs.auto.screen;

import com.guozinhs.auto.core.StateNode;
import com.guozinhs.auto.log.Logger;
import com.guozinhs.auto.match.MyImageMatcher;
import com.guozinhs.auto.match.PointInfo;
import com.guozinhs.auto.util.image.ImageUtils;
import lombok.Data;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;

/**
 * 屏幕截图
 *
 * @Author: GuoZi
 * @Date: 2022/1/8 16:38
 */
@Data
public class ScreenCapture {

    /**
     * 鼠标等待时间
     */
    private static final Long TIME_MS_WAIT_MOUSE = 3000L;

    private Rectangle range;
    private final Robot robot;
    private final Logger log;

    public ScreenCapture(Robot robot, Logger log) {
        this.robot = robot;
        this.log = log;
        this.reset();
    }

    /**
     * 重置截图范围
     */
    public void reset() {
        GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice device = graphicsEnvironment.getDefaultScreenDevice();
        Rectangle bounds = device.getDefaultConfiguration().getBounds();
        DisplayMode displayMode = device.getDisplayMode();
        this.range = new Rectangle(bounds.x, bounds.y, displayMode.getWidth(), displayMode.getHeight());
    }

    /**
     * 设置截图范围
     *
     * @param locationNode 定位数据
     * @param imagePath    匹配图片地址
     * @return 定位结果
     */
    public boolean locateWindow(StateNode locationNode, String imagePath) {
        this.reset();
        Point matchPoint;
        Long width = locationNode.getWidth();
        Long height = locationNode.getHeight();
        Long offsetX = locationNode.getOffsetX();
        Long offsetY = locationNode.getOffsetY();
        File image = new File(imagePath);
        Double matchPercent = locationNode.getMatchPercent();
        if (Double.compare(0, matchPercent) >= 0 || !image.exists()) {
            // 无需匹配, 直接将(0,0)坐标当作匹配点
            matchPoint = new Point();
        } else {
            BufferedImage screen = this.capture();
            BufferedImage template = ImageUtils.read(imagePath);
            PointInfo matchResult = MyImageMatcher.match(screen, template);
            matchPoint = matchResult.getPoint();
            double matchValue = matchResult.getMatchPercent();
            if (Double.compare(matchValue, matchPercent) < 0) {
                return false;
            }
        }
        this.range = new Rectangle((int) (matchPoint.x + offsetX), (int) (matchPoint.y + offsetY), Math.toIntExact(width), Math.toIntExact(height));
        return true;
    }

    /**
     * 截图
     *
     * @return 图像数据
     */
    public BufferedImage capture() {
        return this.robot.createScreenCapture(this.range);
    }

}
